package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.isoft.c2team3service2.dto.HotNewsDTO;
import com.isoft.c2team3service2.entity.HotNews;
import com.isoft.c2team3service2.mapper.HotNewsMapper;
import com.isoft.c2team3service2.service.FileService;
import com.isoft.c2team3service2.service.HotNewsService;
import com.isoft.c2team3service2.service.SensitiveWordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.isoft.c2team3service2.util.RedisConstants.HOT_NEWS;
import static com.isoft.c2team3service2.util.RedisConstants.HOT_POST;

@Service
@RequiredArgsConstructor
public class HotNewsServiceImpl implements HotNewsService {

    private final HotNewsMapper hotNewsMapper;
    private final FileService fileService;
    private final ObjectMapper objectMapper;
    private final SensitiveWordService sensitiveWordService;
    private final StringRedisTemplate stringRedisTemplate;

    // 1. 查询所有热点新闻（前3条，按创建时间倒序）
    @Override
    public List<HotNewsDTO> getHotNewsList() {
        List<HotNews> newsList = hotNewsMapper.selectList(
                new QueryWrapper<HotNews>()
                        .orderByDesc("created_time")
                        .last("LIMIT 3")
        );

        try {
            String jsonValue = objectMapper.writeValueAsString(newsList);
            stringRedisTemplate.opsForValue().set(HOT_NEWS, jsonValue);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return convertToDTOList(newsList);
    }

    // 2. 根据ID查询单条新闻
    @Override
    public HotNewsDTO getHotNewsById(Long id) {
        HotNews hotNews = hotNewsMapper.selectById(id);
        if (hotNews == null) {
            throw new MybatisPlusException("热点新闻不存在，ID：" + id);
        }
        return convertToDTO(hotNews);
    }

    // 3. 创建热点新闻
    // 1. 添加热点新闻：返回boolean（成功/失败）
    @Override
    public boolean createHotNews(HotNewsDTO hotNewsDTO, MultipartFile file) {
        HotNews hotNews = new HotNews();
        String filteredContent = sensitiveWordService.filterText(hotNewsDTO.getContent());
        String filterTitle =  sensitiveWordService.filterText(hotNewsDTO.getTitle());

        if (filteredContent.endsWith("（敏感词）") || filterTitle.endsWith("（敏感词）")) {
            throw new IllegalArgumentException("内容或标题包含敏感词请重新输入");
        }else {
            hotNews.setTitle(hotNewsDTO.getTitle());
            hotNews.setContent(hotNewsDTO.getContent());
            hotNews.setBackgroundImg(hotNewsDTO.getBackgroundImg());
            hotNews.setCreatedTime(LocalDateTime.now());

            if (file != null) {
                String s = fileService.rePhoto(file, "howNews");
                hotNews.setBackgroundImg(s);
            }

            // 插入成功返回1，失败返回0 → 转boolean
            int insertRows = hotNewsMapper.insert(hotNews);
            return insertRows > 0;
        }
    }

    // 4. 更新热点新闻
    @Override
    public boolean updateHotNews(Long id, HotNewsDTO hotNewsDTO, MultipartFile file) {
        // 1. 原有校验：新闻是否存在
        HotNews existingNews = hotNewsMapper.selectById(id);
        if (existingNews == null) {
            throw new MybatisPlusException("热点新闻不存在，ID：" + id);
        }

        // 2. 原有逻辑：更新非空字段
        if (hotNewsDTO.getTitle() != null) {
            existingNews.setTitle(hotNewsDTO.getTitle());
        }
        if (hotNewsDTO.getContent() != null) {
            existingNews.setContent(hotNewsDTO.getContent());
        }
        if (hotNewsDTO.getBackgroundImg() != null && file != null) {
            existingNews.setBackgroundImg(fileService.rePhoto(file, "howNews"));
        }

        String filteredContent = sensitiveWordService.filterText(hotNewsDTO.getContent());
        String filterTitle =  sensitiveWordService.filterText(hotNewsDTO.getTitle());

        if (filteredContent.endsWith("（敏感词）") || filterTitle.endsWith("（敏感词）")) {
            throw new IllegalArgumentException("内容或标题包含敏感词请重新输入");
        }else {
            // 3. 关键：通过更新行数判断成功/失败（返回1=成功，0=失败）
            int updateRows = hotNewsMapper.updateById(existingNews);
            return updateRows > 0;
        }
    }

    // 5. 删除热点新闻
    // 2. 删除热点新闻：返回boolean（成功/失败）
    @Override
    public boolean deleteHotNews(Long id) {
        // 校验新闻是否存在
        HotNews hotNews = hotNewsMapper.selectById(id);
        if (hotNews == null) {
            throw new MybatisPlusException("热点新闻不存在，ID：" + id);
        }

        // 删除成功返回1，失败返回0 → 转boolean
        int deleteRows = hotNewsMapper.deleteById(id);
        return deleteRows > 0;
    }

    // 工具方法：Entity转DTO
    private HotNewsDTO convertToDTO(HotNews hotNews) {
        HotNewsDTO dto = new HotNewsDTO();
        dto.setId(hotNews.getId());
        dto.setTitle(hotNews.getTitle());
        dto.setContent(hotNews.getContent());
        dto.setBackgroundImg(hotNews.getBackgroundImg());
        dto.setCreatedTime(hotNews.getCreatedTime());
        return dto;
    }

    // 工具方法：Entity列表转DTO列表
    private List<HotNewsDTO> convertToDTOList(List<HotNews> newsList) {
        return newsList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
}